package com.village.friend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.village.friend.constant.ChatWords;
import com.village.friend.constant.MsgCodeEnum;
import com.village.friend.constant.TimeType;
import com.village.friend.dto.request.*;
import com.village.friend.dto.response.ActivityListResDto;
import com.village.friend.dto.response.BaseResponse;
import com.village.friend.entity.Activity;
import com.village.friend.entity.ActivityJoin;
import com.village.friend.entity.User;
import com.village.friend.redis.RedisService;
import com.village.friend.service.ActivityJoinService;
import com.village.friend.service.ActivityService;
import com.village.friend.service.OpenImService;
import com.village.friend.service.impl.UserServiceImpl;
import com.village.friend.utils.ParamUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author yl
 * @since 2021-08-13
 */
@Api(tags = "活动管理")
@RestController
@RequestMapping("/activity")
public class ActivityController extends BaseController {
    @Autowired
    public ActivityService activityService;
    @Autowired
    public UserServiceImpl userService;
    @Autowired
    public ActivityJoinService activityJoinService;
    @Autowired
    RedisService redisService;
    @Autowired
    OpenImService openImService;

    @ApiOperation("发布活动")
    @PostMapping("/add")
    public BaseResponse<String> add(@RequestBody ActivityAddDto param) {
        User userRedis = redisService.getUser(param.getToken());
        Integer userId = userRedis.getUid();
        User userEntity = userService.getUserByUserId(userId, userRedis.getLongitude(), userRedis.getLatitude());
        userEntity.setToken(param.getToken());

        //具体时间 需要判断是否传递日期过期
        if (param.getTimeType() == TimeType.SPECTIME.getCode() && param.getTime() == null) {
            BaseResponse<String> error = new BaseResponse(MsgCodeEnum.PARAMS_ERROR, null);
            error.setMsg("请选择具体时间");
            return error;
        }

        // 请求实体 转为 数据库实体
        Activity entity = new Activity();
        BeanUtils.copyProperties(param, entity, "images", "time");
        if (param.getTimeType() == TimeType.SPECTIME.getCode() && param.getTime() != null) {
            entity.setTime(LocalDateTime.parse(param.getTime() + ":00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        entity.setImages(ParamUtils.listToJSONStr(param.getImages()));
        entity.setUserId(userRedis.getUid());
        entity.setStatus(1);
        if (StringUtils.isEmpty(param.getCity())) {
            entity.setCity(userEntity.getCity());
        }
        activityService.save(entity);

        openImService.sendMsgByManager(entity.getUserId(), ChatWords.ADD_ACTIVITY_SUCCESS);
        return new BaseResponse(MsgCodeEnum.SUCCESS, null);
    }

    @ApiOperation(value = "更新活动状态", httpMethod = "POST")
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public BaseResponse<String> updateActivityStatus(@RequestBody ActivityStatusDto param) {
        User userRedis = redisService.getUser(param.getToken());
        Activity activity = activityService.getById(param.getId());
        Integer userIdRedis = userRedis.getUid();
        Integer userIdActivity = activity.getUserId();
        if ((activity == null) || (userIdRedis > userIdActivity) || (userIdRedis < userIdActivity)) {
            return new BaseResponse(MsgCodeEnum.OTHER_ERROR, "不能修改别人的活动");
        }
        // 请求实体 转为 数据库实体
        activityService.updateStatus(param.getId(), param.getStatus());
        return new BaseResponse(MsgCodeEnum.SUCCESS, null);
    }

    @ApiOperation("报名")
    @PostMapping("/join")
    public BaseResponse<String> join(@RequestBody ActivityJoinDto param) {
        User userRedis = redisService.getUser(param.getToken());

        Activity activity = activityService.getById(param.getId());
        if (activity == null) {
            return new BaseResponse(MsgCodeEnum.OTHER_ERROR, "活动不存在");
        }
        if (userRedis.getUid() == activity.getUserId()) {
            return new BaseResponse(MsgCodeEnum.OTHER_ERROR, "不能报名自己的活动奥");
        }
        activityJoinService.insertOrUpdate(activity.getId(), activity.getUserId(), userRedis.getUid(), param.getIsJoin());
        return new BaseResponse(MsgCodeEnum.SUCCESS, null);
    }

    @ApiOperation(value = "同意用户报名", httpMethod = "POST")
    @RequestMapping(value = "/agree", method = RequestMethod.POST)
    public BaseResponse<String> agree(@RequestBody ActivityAgreeDto param) {
        User userRedis = redisService.getUser(param.getToken());
        Activity activity = activityService.getById(param.getId());
        Integer userIdRedis = userRedis.getUid();
        Integer userIdActivity = activity.getUserId();
        if ((activity == null) || (userIdRedis > userIdActivity) || (userIdRedis < userIdActivity)) {
            return new BaseResponse(MsgCodeEnum.OTHER_ERROR, "不能同意别人的活动");
        }
        activityJoinService.insertOrUpdateAgree(param.getId(), userRedis.getUid(), param.getUserIdJoin(), param.getIsAgree());
        return new BaseResponse(MsgCodeEnum.SUCCESS, null);
    }

    @ApiOperation(value = "活动,我的活动(我发起的，我参与的)")
    @GetMapping("/page")
    public BaseResponse<IPage<ActivityListResDto>> userPage(ActivityListDto param) {
        String city = param.getCity();
        if ("不限地区".equals(city)) {
            param.setCity(null);
        }
        Integer type = param.getType();
        if (type == null || type == 0) {
            param.setType(null);
        }
        Integer gender = param.getGender();
        if (gender == null || gender == 0) {
            param.setGender(null);
        } else {
            param.setGender(gender - 1);
        }
        User userRedis = redisService.getUser(param.getToken());
        // 查询用户信息
        IPage<ActivityListResDto> pageData = new Page<>(param.getPage(), param.getLimit());
        Integer limit = param.getLimit();
        Integer offset = (param.getPage() - 1) * limit;

        List<Activity> list;
        Integer total;
        Integer ower = param.getOwer();
        if (ower == 1) {
            // 1,发起的
            list = activityService.list(userRedis.getUid(), null, userRedis.getUid(), param.getType(), param.getGender(), param.getCity(), userRedis.getLatitude(), userRedis.getLongitude(), limit, offset);
            total = activityService.listCount(userRedis.getUid(), null, userRedis.getUid(), param.getType(), param.getGender(), param.getCity());
        } else if (ower == 2) {
            // 2,参与的
            list = activityService.list(null, userRedis.getUid(), userRedis.getUid(), param.getType(), param.getGender(), param.getCity(), userRedis.getLatitude(), userRedis.getLongitude(), limit, offset);
            total = activityService.listCount(null, userRedis.getUid(), userRedis.getUid(), param.getType(), param.getGender(), param.getCity());
        } else {
            //  全部
            list = activityService.list(null, null, userRedis.getUid(), param.getType(), param.getGender(), param.getCity(), userRedis.getLatitude(), userRedis.getLongitude(), limit, offset);
            total = activityService.listCount(null, null, userRedis.getUid(), param.getType(), param.getGender(), param.getCity());
        }
        List<ActivityListResDto> dataList = new ArrayList<>();
        for (Activity activity : list) {
            ActivityListResDto data = new ActivityListResDto();
            BeanUtils.copyProperties(activity, data, "images");
            data.setImages(ParamUtils.jsonStrToList(activity.getImages()));

            Integer vipLeft = activity.getVipLeft();
            if (vipLeft <= 0) {
                vipLeft = 0;
            }
            if (activity.getVipLevel() == 2) {
                // 永久会员
                vipLeft = 10000;
            }
            data.setVipLeft(vipLeft);
            dataList.add(data);
        }
        pageData.setTotal(total);
        pageData.setRecords(dataList);
        return new BaseResponse(MsgCodeEnum.SUCCESS, pageData);
    }

    @ApiOperation(value = "首页:Ta的活动")
    @GetMapping("/page/home")
    public BaseResponse<IPage<ActivityListResDto>> getUserActivityPage(ActivityUserListDto param) {
        User userRedis = redisService.getUser(param.getToken());
        IPage<ActivityListResDto> pageData = new Page<>(param.getPage(), param.getLimit());
        Integer limit = param.getLimit();
        Integer offset = (param.getPage() - 1) * limit;
        List<Activity> list = activityService.list(param.getUserIdLooked(), null, userRedis.getUid(), null, null, null, userRedis.getLatitude(), userRedis.getLongitude(), limit, offset);
        Integer total = activityService.listCount(param.getUserIdLooked(), null, userRedis.getUid(), null, null, null);
        List<ActivityListResDto> dataList = new ArrayList<>();
        for (Activity activity : list) {
            ActivityListResDto data = new ActivityListResDto();
            BeanUtils.copyProperties(activity, data, "images");
            data.setImages(ParamUtils.jsonStrToList(activity.getImages()));
            dataList.add(data);
        }
        pageData.setTotal(total);
        pageData.setRecords(dataList);
        return new BaseResponse(MsgCodeEnum.SUCCESS, pageData);
    }

    @ApiOperation(value = "活动参与用户列表")
    @GetMapping("/page/join")
    public BaseResponse<IPage<ActivityJoin>> item(ActivityJoinUserDto param) {
        IPage<ActivityJoin> pageData = new Page(param.getPage(), param.getLimit());
        Integer limit = param.getLimit();
        Integer offset = (param.getPage() - 1) * limit;
        List<ActivityJoin> joinList = activityJoinService.getJoinList(param.getId(), offset, limit);
        Integer total = activityJoinService.getJoinCount(param.getId());
        pageData.setRecords(joinList);
        pageData.setTotal(total);
        return new BaseResponse(MsgCodeEnum.SUCCESS, pageData);
    }
}

